package com.spring.housing.service.userInfoService;

import com.spring.housing.acceptType.PageParams;
import com.spring.housing.constant.Constants;
import com.spring.housing.redisConfig.DistributedRedisLock;
import com.spring.housing.returnType.CommenResult;
import com.spring.housing.returnType.PageType;
import com.spring.housing.util.DateUtils;
import com.spring.housing.util.QueryTemplateForJdbc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class NewsInfoServer {
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
RedisTemplate redisTemplate;
    /**
     *
     * @param params newsDate---eg:20220307 按日期查询可以为空 ----houseId 必传 指定区域码
     * @return  list
     */
    public CommenResult<PageType<Map<String,Object>>> newsInfo(PageParams params){
        String  sql ="select news_desc,DATE_FORMAT(news_date,'%Y-%m-%d') as news_date,house_desc,b.house_main from (select news_desc,news_date,which_house_id from news where status =1 ";
        Object [] objects = new Object[3];

        //重新定位后 更改Redis用户位置位置信息eg:100-200
        Long expire = redisTemplate.opsForValue().getOperations().getExpire(Constants.UserINFO,TimeUnit.MINUTES);
        List<Map<String,String>> o = (List<Map<String, String>>) redisTemplate.opsForValue().get(Constants.UserINFO);
        Map<String,String> newUserInfoMaP= new HashMap<>();
//        用户首次进入时没有houId情况
        if(params.getParam().get("houseId").toString().equals("")) {
            List<Map<String, String>> user = (List<Map<String, String>>) redisTemplate.opsForValue().get(Constants.UserINFO);
            Map<String, Object> m = new HashMap();
            m.put("houseId", user.get(0).get("adress"));
            params.setParam((HashMap<String, Object>) m);
        }
        Map<String, Object> map1 = jdbcTemplate.queryForMap("select distinct house_main from area_house where house_id like concat(?,'%')", params.getParam().get("houseId").toString());
        newUserInfoMaP.putAll(o.get(0));
        newUserInfoMaP.remove("adress");
        newUserInfoMaP.remove("adress_name");
        newUserInfoMaP.put("adress",params.getParam().get("houseId").toString());
        newUserInfoMaP.put("adress_name",map1.get("house_main").toString());
        List<Map<String,String>> newUserInfoList = new ArrayList<>();
        newUserInfoList.add(newUserInfoMaP);
        redisTemplate.delete(Constants.UserINFO);
        redisTemplate.opsForValue().set(Constants.UserINFO,newUserInfoList,expire,TimeUnit.MINUTES);
        log.info(((List<Map<String, String>>) redisTemplate.opsForValue().get(Constants.UserINFO)).toArray().toString());
        //支持按时间条件查询
        if(params.getParam().get("newsDate")!=null&&!"".equals(params.getParam().get("newsDate"))){
            sql+="and DATE_FORMAT(news_date,'%Y%m%d')  ="+params.getParam().get("newsDate");
        }
        sql +=")a JOIN (select  house_desc,house_id,house_main from area_house where house_id like  concat(?,'%') )b on a.which_house_id=b.house_id order by 2 limit ?,? ";
        log.info(sql);
         objects[0]=params.getParam().get("houseId");
        objects[1]=(params.getPageReq().getPageNo()-1)*params.getPageReq().getPageSize();
        objects[2]=params.getPageReq().getPageSize();
        //将定位的位置信息放进redis里面
       List <Map<String, Object> >map = jdbcTemplate.queryForList("select  location_x,location_y from area_house where house_id like  concat(?,'%') group  by house_main", params.getParam().get("houseId"));

       if(redisTemplate.opsForValue().get(Constants.LOCATION) !=null){
            redisTemplate.delete(Constants.LOCATION);
        }

        redisTemplate.opsForValue().set(Constants.LOCATION,map.toArray(),125, TimeUnit.MINUTES);


        List<Map<String, Object>> list2 = jdbcTemplate.queryForList("select staticValue from static_value where staticTypeId =? and status=1", params.getParam().get("houseId"));
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, objects);
        list.addAll(list2);
        List<Map<String, Object>> list1 = jdbcTemplate.queryForList("select count(*)  from news where which_house_id like  concat(?,'%')",params.getParam().get("houseId"));
        PageType pageType = new PageType(Integer.parseInt(list1.get(0).get("count(*)").toString()),params.getPageReq().getPageNo(),params.getPageReq().getPageSize(),list.toArray());

        return new CommenResult<>(200,"新闻查询成功!",pageType) ;
    }

    /**
     * ofc的业务信息查询
     * @param params 分页信息
     * @return
     */
    public CommenResult<PageType<Map<String, Object>>> ofckbInfo(PageParams params)  {
        List<Map<String, Object>> userInfo = (List<Map<String, Object>>) redisTemplate.opsForValue().get(Constants.UserINFO);
        try{
            if(userInfo==null){
                throw new Exception("登录信息失效!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        List par = new ArrayList();
        List par2 = new ArrayList();
        String adress = userInfo.get(0).get("adress").toString();
        String  sql ="select DATE_FORMAT(a.date,'%Y-%m-%d') as dates, a.id,a.area,a.descs,a.destination,a.money,a.order_code,a.order_phone,a.state  from d_ofc a where a.area like \n" +
                "CONCAT(?,'%')";
        par.add(adress);
        if(params.getParam().get("destination")!=null){
            sql +="and a.destination like CONCAT('%',?,'%')";
            par.add(params.getParam().get("destination").toString());
        }
        sql +=" and DATE_FORMAT(a.date,'%Y-%m-%d') >=? and  DATE_FORMAT(a.date,'%Y-%m-%d') <=? and a.state <>'0' order by 1 limit ?,? ";
        par.add(DateUtils.format(DateUtils.plusDays(new Date(),-7L),"yyyy-MM-dd"));
        par.add(DateUtils.format(new Date(),"yyyy-MM-dd"));
        par.add((params.getPageReq().getPageNo()-1)*params.getPageReq().getPageSize());
        par.add(params.getPageReq().getPageSize());

        String sql_total ="select count(*) as counts   from d_ofc a where a.area like " +
                "CONCAT(?,'%')";
        par2.add(adress);
        if(params.getParam().get("destination")!=null){
            sql_total +="and a.destination like CONCAT('%',?,'%')";
            par2.add(params.getParam().get("destination").toString());
        }
        sql_total +=" and DATE_FORMAT(a.date,'%Y-%m-%d') >=? and  DATE_FORMAT(a.date,'%Y-%m-%d') <=? and a.state <>'0' order by 1 ";
        par2.add(DateUtils.format(DateUtils.plusDays(new Date(),-7L),"yyyy-MM-dd"));
        par2.add(DateUtils.format(new Date(),"yyyy-MM-dd"));
        List <Map<String, Object> >list2 = jdbcTemplate.queryForList(sql_total, par2.toArray());

        List <Map<String, Object> >list1 = jdbcTemplate.queryForList(sql, par.toArray());
        PageType pageType = new PageType(Integer.parseInt(list2.get(0).get("counts").toString()),params.getPageReq().getPageNo(),params.getPageReq().getPageSize(),list1.toArray());


        return new CommenResult<PageType<Map<String, Object>>>(200,"ofc查询成功!",pageType) ;
    }

    public static void main(String[] args) {
        String format = DateUtils.format(DateUtils.plusDays(new Date(), -7L), "yyyy-MM-dd");

        System.out.println(DateUtils.format(new Date(),"yyyy-MM-dd"));
    }

    //接单中心

    @Transactional(rollbackFor = Exception.class)
    public CommenResult acceptOder(PageParams page) {
        String id = page.getParam().get("id").toString();
        //正在抢单
        DistributedRedisLock.acquire(id);
        try{
            String sql ="select * from d_ofc where id =?";
            Map<String, Object> list = jdbcTemplate.queryForMap(sql, id);
            List <Map<String,String> >o = (List<Map<String, String>>) redisTemplate.opsForValue().get(Constants.UserINFO);
            String ownphone = o.get(0).get("phone");
            String adress = o.get(0).get("adress");
            String call = o.get(0).get("call");
            //将订单状态改为接单状态
            int update = jdbcTemplate.update("update  d_ofc set state =2 where id =?", id);
            if(update==0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new CommenResult(201,"接单失败请稍后重试!","");
            }
            //将数据送往我的处理中心页面
            String sqlup ="insert into handel_center(order_phone,order_code,state,descs,destination,money,area,acc_date,own_phone)" +
                    "values(?,?,?,?,?,?,?,?,?)";
            List<Object> arr = new ArrayList<>(10);
            arr.add(list.get("order_phone").toString());
            arr.add(list.get("order_code").toString());
            arr.add("1");
            arr.add(list.get("descs").toString());
            arr.add(list.get("destination").toString());
            String money = list.get("money").toString().split(":")[0];
            arr.add(money);
            arr.add(adress);
            arr.add(new Date() );
            arr.add(ownphone);
            int update1 = jdbcTemplate.update(sqlup, arr.toArray());
            if(update1==0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new CommenResult(201,"接单失败请稍后重试!","");

            }
            //发送消息到对方消息中心


            List<Object> m = new ArrayList<>();
            m.add("客官您好，您的物品将从"+list.get("descs").toString()+"送达"+list.get("destination").toString());
            m.add(ownphone);
            m.add(call);
            m.add(new Date());
            m.add(list.get("order_phone").toString());
            Map<String, Object> map = jdbcTemplate.queryForMap("select * from user where phone=?", list.get("order_phone").toString());
            m.add(map.get("call").toString());

            m.add("https://img1.baidu.com/it/u=3680320999,4108379159&fm=253&fmt=auto&app=138&f=PNG?w=518&h=500");
            m.add("1");
            m.add(map.get("sex").toString());

            String  sql1 ="insert into  message_center(descs,s_phone,s_name,e_date,r_phone,r_name,desc_img,state,s_sex) values(?,?,?,?,?,?,?,?,?)";


            jdbcTemplate.update(sql1,m.toArray());
            return new CommenResult(200,"接单成功!","接单成功!");
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new CommenResult(201,"接单失败请稍后重试!","");

        }
    }
}
